package com.meitianhui.convenitenbuy.module.home.presenter;

import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseResponse;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.http.ResponseObserver;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.module.home.contract.SubmitOrderContract;
import com.meitianhui.convenitenbuy.module.home.http.HomeApiDataSource;
import com.meitianhui.convenitenbuy.module.home.model.bean.SetUpOrderBean;
import com.meitianhui.convenitenbuy.module.home.ui.activity.SubmitOrderActivity;
import com.meitianhui.convenitenbuy.module.mine.model.rxbusBean.RecommenderEventBean;
import com.meitianhui.convenitenbuy.module.wallet.model.AlipayResultBean;
import com.meitianhui.convenitenbuy.module.wallet.model.PayResultBean;
import com.meitianhui.convenitenbuy.module.wallet.model.RechargeBackInfoBean;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.SystemUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by amy on 2018/1/10.
 */

public class SubmitOrderPresenter implements SubmitOrderContract.Presenter {

    private SubmitOrderActivity mContext;
    private SubmitOrderContract.View mView;
    private final IWXAPI wxApi;
    private String dataSourse;

    public SubmitOrderPresenter(SubmitOrderActivity activity, SubmitOrderActivity contact) {
        this.mView = activity;
        this.mContext = contact;
        wxApi = WXAPIFactory.createWXAPI(mContext, Constants.WX_APP_ID, true);
    }

    @Override
    public void attachView(Object view) {
    }

    @Override
    public void detachView() {
    }

    @Override
    public void goToPayMoney(String payWay, String address, String addressName, String addressPhone,
                             String message, String goods_code, String orderType, String amount,
                             String data_source, String quantity, String skuId, boolean flags) {
        JSONObject params = new JSONObject();
        try {
            params.put("goods_code", goods_code);
            params.put("consumer_id", InfoProvider.getUserToken(mContext).getMember_id());
            params.put("recommend_stores_id", InfoProvider.getDefaultStoreId(mContext));
            params.put("mobile", InfoProvider.getUserInfo(mContext).getMobile());
            params.put("order_type", orderType);
            params.put("data_source", Constants.CUSTOM_APP);
            params.put("delivery_address", address);
            params.put("remark", message);
            params.put("contact_person", addressName);
            params.put("contact_tel", addressPhone);
            params.put("nick_name", InfoProvider.getConsumerInfo(App.getInstance()).getNick_name());
            params.put("qty", quantity);
            if (!TextUtils.isEmpty(skuId)) {
                params.put("sku_id", skuId);
                params.put("flags", flags);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        String service = null;
        if (TextUtils.equals(data_source, "huiguo")) {
            //会过的订单
            service = "order.consumer.huiguoOrderCreate";
        } else {
            //自营的订单
            // service = "order.consumer.OwnOrderCreate";
            service = "order.consumer.newOwnOrderCreate";
        }

        HomeApiDataSource.getInstance()
                .setUpOrder(InfoProvider.getUserToken(mContext).getUser_token(), service, params.toString())
                .subscribe(new ResponseObserver<BaseResponse<SetUpOrderBean>>(mContext, true) {
                    @Override
                    public void onSuccess(BaseResponse<SetUpOrderBean> response) {
                        callPayment(response.data.getOrder_id(), payWay, goods_code, amount, data_source);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        mView.payMoneyFail(msg);
                    }
                });
    }

    @Override
    public void callPay(String order_id, String payWay, String goods_code,
                        String amount, String data_source) {
        callPayment(order_id, payWay, goods_code, amount, data_source);
    }

    private void callPayment(String str, String payWay, String goods_code,
                             String amount, String data_sourse) {
        this.dataSourse = data_sourse;
        String service = null;
        Map<String, String> params = new HashMap<>();
        params.put("data_source", Constants.CUSTOM_APP);
        if (TextUtils.equals(data_sourse, "huiguo")) {
            //会过的订单
            params.put("order_type_key", Constants.ORDER_TYPE_KEY_HG);
            service = "finance.consumer.huiguoCreatePay";
        } else {
            //自营的订单
            params.put("order_type_key", Constants.ORDER_TYPE_KEY_ZY);
            service = "finance.consumer.mainOrderPay";
        }
        params.put("payment_way_key", payWay);
        params.put("amount", amount);
        params.put("member_id", InfoProvider.getUserToken(mContext).getMember_id());
        params.put("member_type_key", "consumer");
        params.put("goods_code", goods_code);
        params.put("order_id", str);

        HomeApiDataSource.getInstance()
                .payMoneyHuiGuo(InfoProvider.getUserToken(mContext).getUser_token(),
                        service, new Gson().toJson(params))
                .subscribe(new ResponseObserver<BaseResponse<RechargeBackInfoBean>>(App.getInstance()) {
                    @Override
                    public void onSuccess(BaseResponse<RechargeBackInfoBean> response) {
                        RechargeBackInfoBean result = response.data;
                        if (payWay.equals(Constants.ALIPAY_APY)) {
                            //支付宝支付
                            wakeUpAliPay(result, dataSourse);

                        } else if (payWay.equals(Constants.WECHAT_APY)) {
                            //微信支付
                            wakeUpWeChat(result, dataSourse);
                        }
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        mView.payMoneyFail(msg);
                    }
                });
    }

    public void wakeUpWeChat(RechargeBackInfoBean result, String dataSourse) {
        boolean ifInstall = SystemUtils.isWXAppInstalledAndSupported(mContext, result.getAppid());
        if (!ifInstall) {
            TipUtils.showToast(App.getInstance(), mContext.getString(R.string.wallet_change_recharge_order_wechat_uninstall));
            return;
        }
        PayReq req = new PayReq();
        req.appId = result.getAppid();
        req.nonceStr = result.getNoncestr();
        req.packageValue = result.getPackageValue();
        req.partnerId = result.getPartnerid();
        req.prepayId = result.getPrepayid();
        req.timeStamp = result.getTimestamp();
        req.sign = result.getSign();
        wxApi.registerApp(result.getAppid());
        wxApi.sendReq(req);
        RxBus.get().post(new RecommenderEventBean(dataSourse));
    }

    private void wakeUpAliPay(RechargeBackInfoBean bean, String dataSourse) {
        String orderInfo = bean.getAlipay_params();
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                PayTask alipay = new PayTask(mContext);
                String result = alipay.pay(orderInfo, true);
                emitter.onNext(result);
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                AlipayResultBean payResult = new AlipayResultBean(s);
                String resultInfo = payResult.getResult();
                String resultStatus = payResult.getResultStatus();
                // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                if (TextUtils.equals(resultStatus, "9000")) {
                    TipUtils.showToast(mContext, mContext.getString(R.string.wallet_change_recharge_success), 1);
                    RxBus.get().post(new PayResultBean(Constants.PAY_RESULT_SUCCESS));
                    RxBus.get().post(new EventBean(Constants.EVENT_TYPE_REFRESH));//钱包刷新
                    //通知订单界面去刷新
                    RxBus.get().post(new EventBean(Constants.EVENT_TYPE_ORDER_OPERATION));
                    mView.payMoneySucc();
                } else {
                    // 判断resultStatus 为非“9000”则代表可能支付失败
                    // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，
                    // 最终交易是否成功以服务端异步通知为准（小概率状态）
                    if (TextUtils.equals(resultStatus, "8000")) {
                        TipUtils.showToast(App.getInstance(), mContext.getString(R.string.wallet_change_recharge_confirming), 3);
                    } else {
                        // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                        TipUtils.showToast(App.getInstance(), mContext.getString(R.string.wallet_change_recharge_fail));
                        //如果用户取消支付 就跳到订单页面
                        RxBus.get().post(new PayResultBean(Constants.PAY_RESULT_FAIL_HUIGUO));

                    }
                }
            }
        });
    }

}
